package org.dromara.business.service.impl;

import jakarta.annotation.PostConstruct;
import org.dromara.common.core.constant.CacheNames;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.ObjectUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.redis.utils.CacheUtils;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.dromara.business.domain.bo.RepeaterConfigBo;
import org.dromara.business.domain.vo.RepeaterConfigVo;
import org.dromara.business.domain.RepeaterConfig;
import org.dromara.business.mapper.RepeaterConfigMapper;
import org.dromara.business.service.IRepeaterConfigService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 中继器配置Service业务层处理
 *
 * @author Eric
 * @date 2025-08-31
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class RepeaterConfigServiceImpl implements IRepeaterConfigService {

    private final RepeaterConfigMapper baseMapper;


    /**
     * 查询中继器配置
     *
     * @param id 主键
     * @return 中继器配置
     */
    @Override
    public RepeaterConfigVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询中继器配置列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 中继器配置分页列表
     */
    @Override
    public TableDataInfo<RepeaterConfigVo> queryPageList(RepeaterConfigBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<RepeaterConfig> lqw = buildQueryWrapper(bo);
        Page<RepeaterConfigVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的中继器配置列表
     *
     * @param bo 查询条件
     * @return 中继器配置列表
     */
    @Override
    public List<RepeaterConfigVo> queryList(RepeaterConfigBo bo) {
        LambdaQueryWrapper<RepeaterConfig> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<RepeaterConfig> buildQueryWrapper(RepeaterConfigBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<RepeaterConfig> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(RepeaterConfig::getId);
        lqw.like(StringUtils.isNotBlank(bo.getConfigName()), RepeaterConfig::getConfigName, bo.getConfigName());
        lqw.eq(StringUtils.isNotBlank(bo.getConfigKey()), RepeaterConfig::getConfigKey, bo.getConfigKey());
        lqw.eq(StringUtils.isNotBlank(bo.getConfigValue()), RepeaterConfig::getConfigValue, bo.getConfigValue());
        return lqw;
    }

    /**
     * 新增中继器配置
     *
     * @param bo 中继器配置
     * @return 是否新增成功
     */
    @CachePut(cacheNames = CacheNames.REPEATER_CONFIG, key = "#bo.configKey")
    @Override
    public String insertByBo(RepeaterConfigBo bo) {
        RepeaterConfig add = MapstructUtils.convert(bo, RepeaterConfig.class);
        int row = baseMapper.insert(add);
        if (row > 0) {
            return add.getConfigValue();
        }
        throw new ServiceException("操作失败");
    }

    /**
     * 修改中继器配置
     *
     * @param bo 中继器配置
     * @return 是否修改成功
     */
    @Override
    @CachePut(cacheNames = CacheNames.REPEATER_CONFIG, key = "#bo.configKey")
    public String updateByBo(RepeaterConfigBo bo) {
        int row = 0;
        RepeaterConfig config = MapstructUtils.convert(bo, RepeaterConfig.class);
        if (config.getId() != null) {
            RepeaterConfig temp = baseMapper.selectById(config.getId());
            if (!StringUtils.equals(temp.getConfigKey(), config.getConfigKey())) {
                CacheUtils.evict(CacheNames.SYS_CONFIG, temp.getConfigKey());
            }
            row = baseMapper.updateById(config);
        } else {
            CacheUtils.evict(CacheNames.SYS_CONFIG, config.getConfigKey());
            row = baseMapper.update(config, new LambdaQueryWrapper<RepeaterConfig>()
                .eq(RepeaterConfig::getConfigKey, config.getConfigKey()));
        }
        if (row > 0) {
            return config.getConfigValue();
        }
        throw new ServiceException("操作失败");
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(RepeaterConfig entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除中继器配置信息
     *
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> configIds) {
        List<RepeaterConfig> list = baseMapper.selectByIds(configIds);
        list.forEach(config -> {
            CacheUtils.evict(CacheNames.REPEATER_CONFIG, config.getConfigKey());
        });
        return baseMapper.deleteByIds(configIds) > 0;
    }

    @PostConstruct
    public void init(){
        List<RepeaterConfig> list = baseMapper.selectList();
        for(RepeaterConfig config : list){
            CacheUtils.put(CacheNames.REPEATER_CONFIG, config.getConfigKey(), config.getConfigValue());
        }
    }

    @Cacheable(cacheNames = CacheNames.REPEATER_CONFIG, key = "#configKey")
    @Override
    public String selectConfigByKey(String configKey) {
        RepeaterConfig retConfig = baseMapper.selectOne(new LambdaQueryWrapper<RepeaterConfig>()
            .eq(RepeaterConfig::getConfigKey, configKey));
        return ObjectUtils.notNullGetter(retConfig, RepeaterConfig::getConfigValue, StringUtils.EMPTY);
    }
}
